import { ref, computed, watch, UnwrapNestedRefs } from "vue";

export default function useSelection<T>(sources: T[] | UnwrapNestedRefs<T[]>) {
  const selectedIndex = ref(0);
  const selectedItem = computed(() => sources[selectedIndex.value] || null);
  const isSelected = (index: number) => index === selectedIndex.value;
  const setSelectedIndex = (index: number) => (selectedIndex.value = index);

  watch(
    () => sources.length,
    (newLen, oldLen) => {
      if (newLen < oldLen && selectedIndex.value! >= oldLen - 1) {
        setSelectedIndex(newLen - 1);
      }
    }
  );

  return {
    isSelected,
    selectedIndex,
    selectedItem,
    setSelectedIndex,
  };
}
